package com.kaibing.hotswap.agent;

import java.io.*;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;

public class AgentMain {
    public static void agentmain(String agentArgs, Instrumentation inst) throws IOException, UnmodifiableClassException, ClassNotFoundException {
        System.out.println("agent main-----------------");
        System.out.println(agentArgs);
        System.out.println("again main start");
        String[] split = agentArgs.split(",");
        String redefineClass = split[0];
        String newClassPath = split[1];
        Class[] allLoadedClasses = inst.getAllLoadedClasses();
        for (Class clazz : allLoadedClasses) {
            System.out.println(clazz.getName());
            if(clazz.getName().equals(redefineClass)) {
                String path = newClassPath;
                FileInputStream fileInputStream = new FileInputStream(path);
                byte[] bytes = new byte[fileInputStream.available()];
                fileInputStream.read(bytes);
                ClassDefinition classDefinition = new ClassDefinition(clazz, bytes);
                inst.redefineClasses(classDefinition);
                break;
            }
        }

        System.out.println("agent main over");
        System.out.println("agent main-----------------");
    }
}
